/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.cs576.HyperLinkVideo.authoringtool;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ListSelectionModel;

/**
 *
 * @author Ludo
 */
public class AuthoringToolGUI extends javax.swing.JFrame {

    private ChangeHyperlinkNameDialog dialog;
    private int currentSecondaryVideo;
    private TrackingAreaHandler handler;
    private int countOfHyperlinks; //not number of hyperlinks
    private List<Hyperlink> hyperlinks;

    public void setUpGUI() {
        pVideoSlider.setMinimum(0);
        pVideoSlider.setMaximum(100);
        pVideoSlider.setValue(0);
        sVideoSlider.setMinimum(0);
        sVideoSlider.setMaximum(100);
        sVideoSlider.setValue(0);
        jTextField1.setText("0");
        jTextField2.setText("0");
        jMenu3.add(selectSecondaryVideo);
        jMenu2.add(selectPrimaryVideo);
        jMenu1.add(saveItem);
        jMenu1.add(exitItem);
        hyperLinkList.setModel(new DefaultListModel());
        hyperLinkList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        hyperLinkList.addListSelectionListener(new HyperlinkListHandler(this));
        keyFrameList.setModel(new DefaultListModel());
        keyFrameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        keyFrameList.addListSelectionListener(new KeyFrameListHandler(this));
        hyperlinks = new ArrayList<Hyperlink>();

        dialog = new ChangeHyperlinkNameDialog(this, true);
        dialog.setGUI(this);


    }

    /**
     * Creates new form AuthoringToolGUI
     */
    public AuthoringToolGUI() {
        currentSecondaryVideo = -1;
        countOfHyperlinks = 0;
        initComponents();
        setUpGUI();
    }

    public void updateLinkVideo(int hyperlinkInd) {
        if (hyperlinks.size() > hyperlinkInd) {
            String name = hyperlinks.get(hyperlinkInd).getLinkVideoName();
            int frame = hyperlinks.get(hyperlinkInd).getLinkVideoStartFrame();
            String text = name;
            if (!name.equals("None")) {
                text += "    frame: " + frame;
            }
            currentLinkVideoName.setText(text);
            this.setFrameForPanel(pVideoSlider.getValue(), true);
        } else if (hyperlinks.size() == hyperlinkInd) {
            //adding a hyperlink, before it's been added to hyperlinks list
            currentLinkVideoName.setText("None");
            this.setFrameForPanel(pVideoSlider.getValue(), true);
        }
    }

    public void updateKeyFrameList(int index) {
        if (hyperlinks.size() > index) {
            DefaultListModel model = hyperlinks.get(index).getKeyFrameModel();
            if (model == null) {
                keyFrameList.setModel(new DefaultListModel());
            } else {
                keyFrameList.setModel(model);
            }
        } else if (hyperlinks.size() == index) {
            //just added a new hyperlink. No KeyFrames
            keyFrameList.setModel(new DefaultListModel());
        }
    }

    public void goToKeyFrame() {
        int hyperlinkInd = hyperLinkList.getSelectedIndex();
        if (hyperlinkInd >= 0) {
            if (hyperlinks.size() > hyperlinkInd) {
                Hyperlink hyperlink = hyperlinks.get(hyperlinkInd);
                ArrayList<KeyFrame> keyframes = (ArrayList<KeyFrame>) hyperlink.getKeyFrames();
                int keyFrameInd = keyFrameList.getSelectedIndex();
                if (keyFrameInd >= 0) {
                    if (keyframes.size() == keyFrameInd) {
                        //just added a new keyframe. No Need to go to it.
                    } else {
                        int frameNum = keyframes.get(keyFrameInd).getFrame();
                        setFrameForPanel(frameNum, true);
                        handler.setTrackingArea(keyframes.get(keyFrameInd).getTrackingArea());
                    }
                }
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        selectSecondaryVideo = new javax.swing.JMenuItem();
        selectPrimaryVideo = new javax.swing.JMenuItem();
        exitItem = new javax.swing.JMenuItem();
        saveItem = new javax.swing.JMenuItem();
        pVideoSlider = new javax.swing.JSlider();
        sVideoSlider = new javax.swing.JSlider();
        secondaryVideoPanel = new com.edu.cs576.HyperLinkVideo.authoringtool.SecondaryVideoViewPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton4 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jButton5 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator3 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        hyperLinkList = new javax.swing.JList();
        addHyperLinkButton = new javax.swing.JButton();
        deleteHyperLinkButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        keyFrameList = new javax.swing.JList();
        addKeyFrameButton = new javax.swing.JButton();
        deleteKeyFrameButton = new javax.swing.JButton();
        currentLinkVideoName = new javax.swing.JLabel();
        connectVideoButton = new javax.swing.JButton();
        jSeparator5 = new javax.swing.JSeparator();
        ModifyKeyFrameButton = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        trackHyperlinkButton = new javax.swing.JButton();
        primaryVideoPanel = new com.edu.cs576.HyperLinkVideo.authoringtool.PrimaryVideoViewPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();

        selectSecondaryVideo.setText("From File System");
        selectSecondaryVideo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectSecondaryVideoActionPerformed(evt);
            }
        });

        selectPrimaryVideo.setText("From File System");
        selectPrimaryVideo.setToolTipText("");
        selectPrimaryVideo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectPrimaryVideoActionPerformed(evt);
            }
        });

        exitItem.setText("Exit");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });

        saveItem.setText("Save File");
        saveItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveItemActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pVideoSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                pVideoSliderStateChanged(evt);
            }
        });

        sVideoSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sVideoSliderStateChanged(evt);
            }
        });

        javax.swing.GroupLayout secondaryVideoPanelLayout = new javax.swing.GroupLayout(secondaryVideoPanel);
        secondaryVideoPanel.setLayout(secondaryVideoPanelLayout);
        secondaryVideoPanelLayout.setHorizontalGroup(
            secondaryVideoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 352, Short.MAX_VALUE)
        );
        secondaryVideoPanelLayout.setVerticalGroup(
            secondaryVideoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 288, Short.MAX_VALUE)
        );

        jPanel2.setToolTipText("");

        jButton4.setText("OK");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jTextField1.setColumns(4);
        jTextField1.setText("jTextField1");

        jLabel1.setText("Frame:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(38, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton4)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1))
        );

        jButton5.setText("OK");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jTextField2.setColumns(4);
        jTextField2.setText("jTextField2");

        jLabel2.setText("Frame:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(37, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton5))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton5)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
        );

        jLabel3.setText("HyperLinks");

        jLabel6.setText("KeyFrames");

        jLabel7.setText("Link Video");

        jScrollPane2.setViewportView(hyperLinkList);

        addHyperLinkButton.setText("Add");
        addHyperLinkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addHyperLinkButtonActionPerformed(evt);
            }
        });

        deleteHyperLinkButton.setText("Delete");
        deleteHyperLinkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteHyperLinkButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(keyFrameList);

        addKeyFrameButton.setText("Add");
        addKeyFrameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addKeyFrameButtonActionPerformed(evt);
            }
        });

        deleteKeyFrameButton.setText("Delete");
        deleteKeyFrameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteKeyFrameButtonActionPerformed(evt);
            }
        });

        currentLinkVideoName.setText("None");

        connectVideoButton.setText("Connect Video");
        connectVideoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectVideoButtonActionPerformed(evt);
            }
        });

        ModifyKeyFrameButton.setText("Modify");
        ModifyKeyFrameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ModifyKeyFrameButtonActionPerformed(evt);
            }
        });

        jButton7.setText("Rename");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        trackHyperlinkButton.setText("Automatic Tracking");
        trackHyperlinkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                trackHyperlinkButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addComponent(jSeparator3)
            .addComponent(jSeparator2)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jSeparator5)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(currentLinkVideoName)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(connectVideoButton))
                            .addComponent(jScrollPane2)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(addHyperLinkButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(deleteHyperLinkButton)
                                .addGap(31, 31, 31)
                                .addComponent(jButton7))
                            .addComponent(jScrollPane1)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(addKeyFrameButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(30, 30, 30)
                                .addComponent(deleteKeyFrameButton)
                                .addGap(35, 35, 35)
                                .addComponent(ModifyKeyFrameButton)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addComponent(trackHyperlinkButton)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addHyperLinkButton)
                    .addComponent(deleteHyperLinkButton)
                    .addComponent(jButton7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addKeyFrameButton)
                    .addComponent(deleteKeyFrameButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ModifyKeyFrameButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(trackHyperlinkButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(currentLinkVideoName)
                    .addComponent(connectVideoButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        primaryVideoPanel.setPreferredSize(new java.awt.Dimension(352, 288));

        javax.swing.GroupLayout primaryVideoPanelLayout = new javax.swing.GroupLayout(primaryVideoPanel);
        primaryVideoPanel.setLayout(primaryVideoPanelLayout);
        primaryVideoPanelLayout.setHorizontalGroup(
            primaryVideoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 352, Short.MAX_VALUE)
        );
        primaryVideoPanelLayout.setVerticalGroup(
            primaryVideoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jButton2.setText("Down");
        jButton2.setToolTipText("");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Up");
        jButton1.setMaximumSize(new java.awt.Dimension(59, 23));
        jButton1.setMinimumSize(new java.awt.Dimension(59, 23));
        jButton1.setPreferredSize(new java.awt.Dimension(59, 23));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton2)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jButton3.setText("Up");
        jButton3.setMaximumSize(new java.awt.Dimension(59, 23));
        jButton3.setMinimumSize(new java.awt.Dimension(59, 23));
        jButton3.setPreferredSize(new java.awt.Dimension(59, 23));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton6.setText("Down");
        jButton6.setToolTipText("");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                    .addComponent(jButton6))
                .addGap(0, 0, 0))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Select PrimaryVideo");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("Select Secondary Video");
        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(primaryVideoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(pVideoSlider, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(sVideoSlider, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(10, 10, 10)
                                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(secondaryVideoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(167, 167, 167)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(secondaryVideoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(primaryVideoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(pVideoSlider, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(sVideoSlider, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        //user wishes to change frame number
        int frameNum = Integer.parseInt(jTextField1.getText());
        if (frameNum <= primaryVideoPanel.getTotalNumberOfFrames()) {
            setFrameForPanel(frameNum, true);
        }

    }//GEN-LAST:event_jButton4ActionPerformed

    private void pVideoSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pVideoSliderStateChanged
        int sliderValue = pVideoSlider.getValue();
        //jTextField1.setText(sliderValue+"");
        setFrameForPanel(sliderValue, true);
    }//GEN-LAST:event_pVideoSliderStateChanged

    private void sVideoSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sVideoSliderStateChanged
        int sliderValue = sVideoSlider.getValue();
        //jTextField2.setText(sliderValue+"");
        setFrameForPanel(sliderValue, false);
    }//GEN-LAST:event_sVideoSliderStateChanged

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        //user wishes to change frame number
        int frameNum = Integer.parseInt(jTextField2.getText());
        if (frameNum <= secondaryVideoPanel.getTotalNumberOfFrames()) {
            setFrameForPanel(500, false);
        }
    }//GEN-LAST:event_jButton5ActionPerformed

	private void selectSecondaryVideoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectSecondaryVideoActionPerformed
            int returnVal = jFileChooser1.showOpenDialog(this);
            if (returnVal == jFileChooser1.APPROVE_OPTION) {
                File file = jFileChooser1.getSelectedFile();
                byte[] secondaryVideo = getVideoFile(file);
                addSecondaryVideo(file.getName(), secondaryVideo);
                secondaryVideoPanel.repaint();
                sVideoSlider.setMaximum(secondaryVideoPanel.getTotalNumberOfFrames());
                sVideoSlider.setValue(0);
            } else {
                System.out.println("File access cancelled by user.");
            }
    }//GEN-LAST:event_selectSecondaryVideoActionPerformed

    private void selectPrimaryVideoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectPrimaryVideoActionPerformed
        int returnVal = jFileChooser1.showOpenDialog(this);
        if (returnVal == jFileChooser1.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            byte[] primaryVideo = getVideoFile(file);
            primaryVideoPanel.setBytes(primaryVideo);
            primaryVideoPanel.setFilename(file.getName());
            primaryVideoPanel.repaint();
            secondaryVideoPanel.repaint();//if we need to remove a secondary video for more java heap space
            pVideoSlider.setMaximum(primaryVideoPanel.getTotalNumberOfFrames());
            pVideoSlider.setValue(0);

            countOfHyperlinks = 0;
            hyperlinks = new ArrayList<Hyperlink>();
            hyperLinkList.setModel(new DefaultListModel());
        } else {
            System.out.println("File access cancelled by user.");
        }
    }//GEN-LAST:event_selectPrimaryVideoActionPerformed

    private void connectVideoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectVideoButtonActionPerformed
        if (secondaryVideoPanel.isVideoSet() && hyperlinks.size() > 0) {
            String filename = secondaryVideoPanel.getCurrentVideoName();
            currentLinkVideoName.setText(filename);
            hyperlinks.get(hyperLinkList.getSelectedIndex()).setLinkVideo(filename, secondaryVideoPanel.getCurrentVideoId(), sVideoSlider.getValue());
            //System.out.println("LinkVideoName: "+filename+"     LinkVideo Start Frame: "+sVideoSlider.getValue());
        }
    }//GEN-LAST:event_connectVideoButtonActionPerformed

    private void addHyperLinkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addHyperLinkButtonActionPerformed
        if (primaryVideoPanel.isVideoSet()) {
            if(handler!= null){
                handler.removeHandler();
            }
            handler = new TrackingAreaHandler(primaryVideoPanel);
            handler.addDefaultRect();
            DefaultListModel model = (DefaultListModel) hyperLinkList.getModel();
            model.addElement("Hyperlink" + countOfHyperlinks);


            if (hyperlinks == null) {
                hyperlinks = new ArrayList<Hyperlink>();
            }
            Hyperlink hyperlink = new Hyperlink(countOfHyperlinks, hyperlinks.size());
            hyperLinkList.setSelectedIndex(hyperlinks.size());

            hyperlinks.add(hyperlink);
            countOfHyperlinks++;
        }
    }//GEN-LAST:event_addHyperLinkButtonActionPerformed

    private void deleteHyperLinkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteHyperLinkButtonActionPerformed
        if (primaryVideoPanel.isVideoSet()) {
            int index = hyperLinkList.getSelectedIndex();
            if (index >= 0) {
                hyperlinks.remove(index);
                DefaultListModel model = (DefaultListModel) hyperLinkList.getModel();
                model.remove(index);
                for (int i = index; i < hyperlinks.size(); i++) {
                    hyperlinks.get(i).setlistIndex(hyperlinks.get(i).getListIndex() - 1);
                }
                if (model.isEmpty()) {
                    countOfHyperlinks = 0;//since no more hyperlinks in list, okay to reset ids to 0.
                }
            }
        }
    }//GEN-LAST:event_deleteHyperLinkButtonActionPerformed

    private void addKeyFrameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addKeyFrameButtonActionPerformed
        if (primaryVideoPanel.isVideoSet() && hyperlinks.size() > 0) {
            TrackingArea currentTrackingArea = primaryVideoPanel.getCurrentTrackingArea();
            int frame = pVideoSlider.getValue();
            if (!isAKeyframe(frame)) {//only add if not already a keyframe

                primaryVideoPanel.setFrame(frame, true);
                KeyFrame keyframe = new KeyFrame(frame);
                keyframe.setCoords(currentTrackingArea);

                int index = hyperLinkList.getSelectedIndex();
                int newInd = hyperlinks.get(index).addKeyFrame(keyframe);
                DefaultListModel model = (DefaultListModel) keyFrameList.getModel();
                model.insertElementAt("frame: " + frame, newInd);
                hyperlinks.get(index).setKeyFrameModel(model);
            }
        }
    }//GEN-LAST:event_addKeyFrameButtonActionPerformed

    private void saveItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveItemActionPerformed
        if (primaryVideoPanel.isVideoSet() && secondaryVideoPanel.isVideoSet()) {
            String output = "";
            for (int i = 0; i < hyperlinks.size(); i++) {
                Hyperlink hyperlink = hyperlinks.get(i);
                int rectID = hyperlink.getID();
                String rectID_string = "";
                if (rectID < 10) {
                    rectID_string = "0" + rectID;
                } else {
                    rectID_string = "" + rectID;
                }
                String rectName = hyperlink.getName();
                ArrayList<KeyFrame> keyframes = (ArrayList<KeyFrame>) hyperlink.getKeyFrames();
                int numOfKeyFrames = keyframes.size();
                output += rectID_string + "     " + rectName + "    " + numOfKeyFrames + "\n";

                String linkVideoName = hyperlink.getLinkVideoName();
                int startFrame = hyperlink.getLinkVideoStartFrame();
                output += linkVideoName + "     " + startFrame + "\n";
                for (int j = 0; j < numOfKeyFrames; j++) {
                    KeyFrame keyframe = keyframes.get(j);
                    int frame = keyframe.getFrame();
                    int[] topLeft = keyframe.getTopLeftCoords();
                    int[] bottomRight = keyframe.getBottomRightCoords();
                    output += frame + "     " + topLeft[0] + "      " + topLeft[1] + "      " + bottomRight[0] + "      " + bottomRight[1] + "\n";
                }
            }
            System.out.println(output);
            saveToSystem(output);
        }
    }//GEN-LAST:event_saveItemActionPerformed

    private void deleteKeyFrameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteKeyFrameButtonActionPerformed
        int index = keyFrameList.getSelectedIndex();
        if (index >= 0) {
            int hindex = hyperLinkList.getSelectedIndex();
            if (hindex >= 0) {
                Hyperlink hyperlink = hyperlinks.get(hindex);
                hyperlink.getKeyFrames().remove(index);
                DefaultListModel model = (DefaultListModel) keyFrameList.getModel();
                model.remove(index);
                hyperlinks.get(hindex).setKeyFrameModel(model);
            }
        }
    }//GEN-LAST:event_deleteKeyFrameButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //move slider up and text box up by one
        int sliderValue = pVideoSlider.getValue();
        if (sliderValue + 1 < primaryVideoPanel.getTotalNumberOfFrames()) {
            setFrameForPanel(sliderValue + 1, true);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int sliderValue = pVideoSlider.getValue();
        if (sliderValue - 1 >= 0) {
            setFrameForPanel(sliderValue - 1, true);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int sliderValue = sVideoSlider.getValue();
        if (sliderValue + 1 < secondaryVideoPanel.getTotalNumberOfFrames()) {
            setFrameForPanel(sliderValue + 1, false);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        int sliderValue = sVideoSlider.getValue();
        if (sliderValue - 1 >= 0) {
            setFrameForPanel(sliderValue - 1, false);
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitItemActionPerformed

    private void ModifyKeyFrameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ModifyKeyFrameButtonActionPerformed
        if (primaryVideoPanel.isVideoSet() && hyperlinks.size() > 0) {
            TrackingArea currentTrackingArea = primaryVideoPanel.getCurrentTrackingArea();
            int frame = pVideoSlider.getValue();
            String selectedKeyframe = (String) keyFrameList.getSelectedValue();
            if (selectedKeyframe != null && selectedKeyframe.equalsIgnoreCase("frame: " + frame)) {//only modify if current frame is same as keyframe
                primaryVideoPanel.setFrame(frame, true);
                KeyFrame keyframe = new KeyFrame(frame);
                keyframe.setCoords(currentTrackingArea);

                int index = hyperLinkList.getSelectedIndex();
                if (index >= 0) {
                    ArrayList<KeyFrame> keyframes = (ArrayList<KeyFrame>) hyperlinks.get(index).getKeyFrames();
                    for (int i = 0; i < keyframes.size(); i++) {
                        if (keyframes.get(i).getFrame() == frame) {
                            keyframes.set(i, keyframe);
                            return;
                        }
                    }
                }
            }
        }
    }//GEN-LAST:event_ModifyKeyFrameButtonActionPerformed

    public void setNewHyperlinkName(String name) {
        int ind = hyperLinkList.getSelectedIndex();
        hyperlinks.get(ind).setName(name);
        DefaultListModel model = (DefaultListModel) hyperLinkList.getModel();
        model.set(ind, name);
    }

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        int ind = hyperLinkList.getSelectedIndex();
        if (ind >= 0) {
            dialog.setVisible(true);
            dialog.validate();
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void trackHyperlinkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trackHyperlinkButtonActionPerformed
        if (primaryVideoPanel.isVideoSet() && hyperlinks.size() > 0) {
            TrackingArea currentTrackingArea = primaryVideoPanel.getCurrentTrackingArea();
            int frame = pVideoSlider.getValue();
            if (!isAKeyframe(frame)) {//only add if not already a keyframe
                this.autoTrack(currentTrackingArea, frame);
            }
        }
    }//GEN-LAST:event_trackHyperlinkButtonActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ModifyKeyFrameButton;
    private javax.swing.JButton addHyperLinkButton;
    private javax.swing.JButton addKeyFrameButton;
    private javax.swing.JButton connectVideoButton;
    private javax.swing.JLabel currentLinkVideoName;
    private javax.swing.JButton deleteHyperLinkButton;
    private javax.swing.JButton deleteKeyFrameButton;
    private javax.swing.JMenuItem exitItem;
    private javax.swing.JList hyperLinkList;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JList keyFrameList;
    private javax.swing.JSlider pVideoSlider;
    private com.edu.cs576.HyperLinkVideo.authoringtool.PrimaryVideoViewPanel primaryVideoPanel;
    private javax.swing.JSlider sVideoSlider;
    private javax.swing.JMenuItem saveItem;
    private com.edu.cs576.HyperLinkVideo.authoringtool.SecondaryVideoViewPanel secondaryVideoPanel;
    private javax.swing.JMenuItem selectPrimaryVideo;
    private javax.swing.JMenuItem selectSecondaryVideo;
    private javax.swing.JButton trackHyperlinkButton;
    // End of variables declaration//GEN-END:variables

    /**
     * Sets the correct frame image, slider position, text field value, for a
     * given panel and frame number
     *
     * @param panel
     * @param frame
     * @param isPrimary if primaryVideoPanel or secondaryVideoPanel
     */
    private void setFrameForPanel(int frame, boolean isPrimary) {
        if (isPrimary) {
            pVideoSlider.setValue(frame);
            if (primaryVideoPanel.isVideoSet()) {
                TrackingArea area = getKeyFrameTrackingArea(frame);
                boolean isKeyframe = false;
                if (area != null) {
                    primaryVideoPanel.setCurrentTrackArea(area);
                    handler.setTrackingArea(area);
                    isKeyframe = true;
                }
                primaryVideoPanel.setFrame(frame, isKeyframe);
            }
            jTextField1.setText(frame + "");
        } else {
            sVideoSlider.setValue(frame);
            if (secondaryVideoPanel.isVideoSet()) {
                secondaryVideoPanel.setFrame(frame);
            }
            jTextField2.setText(frame + "");
        }
    }

    private void autoTrack(TrackingArea currentTrackingArea, int frame) {
        MotionCompensation motion = new MotionCompensation(35);
        TrackingArea area = new TrackingArea();
        int index = hyperLinkList.getSelectedIndex();
        if(index <0){
            return;
        }
        int referenceFrame = frame;
        int maxFrame = primaryVideoPanel.getTotalNumberOfFrames();
        
        while (area != null && referenceFrame < maxFrame) {
            
            int nextFrame = referenceFrame+1;
            
            //setting the original reference frame
            DefaultListModel model = (DefaultListModel) keyFrameList.getModel();
            if(referenceFrame == frame){
                primaryVideoPanel.setFrame(referenceFrame, true);
                KeyFrame keyframe = new KeyFrame(referenceFrame);
                keyframe.setCoords(currentTrackingArea);
                int newInd = hyperlinks.get(index).addKeyFrame(keyframe);
                model.insertElementAt("frame: " + referenceFrame, newInd);
            }
            
            if(!this.isAKeyframe(nextFrame)){
                motion.setReference(primaryVideoPanel.getFrame(referenceFrame), currentTrackingArea);
                motion.setTarget(primaryVideoPanel.getFrame(nextFrame));
                area = motion.getBestMatchingArea();

                //if match area is below error threshold set the new keyframe
                if(area !=null){
                    KeyFrame nextKeyframe = new KeyFrame(nextFrame);
                    nextKeyframe.setCoords(area);
                    int newInd2 = hyperlinks.get(index).addKeyFrame(nextKeyframe);
                    model = (DefaultListModel) keyFrameList.getModel();
                    model.insertElementAt("frame: " + (nextFrame), newInd2);
                    hyperlinks.get(index).setKeyFrameModel(model);
                }
                referenceFrame = nextFrame;
            }else{
                area = null;
            }
        }
    }

    private TrackingArea getKeyFrameTrackingArea(int frameNum) {
        int hInd = hyperLinkList.getSelectedIndex();
        if (hInd >= 0 && hInd < hyperlinks.size()) {
            ArrayList<KeyFrame> keyframes = (ArrayList<KeyFrame>) hyperlinks.get(hInd).getKeyFrames();
            for (int i = 0; i < keyframes.size(); i++) {
                if (keyframes.get(i).getFrame() == frameNum) {
                    return keyframes.get(i).getTrackingArea();
                }
            }
        }
        return null;
    }

    private boolean isAKeyframe(int frameNum) {
        int hInd = hyperLinkList.getSelectedIndex();
        if (hInd >= 0) {
            ArrayList<KeyFrame> keyframes = (ArrayList<KeyFrame>) hyperlinks.get(hInd).getKeyFrames();
            for (int i = 0; i < keyframes.size(); i++) {
                if (keyframes.get(i).getFrame() == frameNum) {
                    return true;
                }
            }
        }
        return false;
    }

    private void addSecondaryVideo(String filename, byte[] secondaryVideo) {

        if (currentSecondaryVideo < 0) {
            currentSecondaryVideo = 0;
        } else {
            currentSecondaryVideo++;
        }
        secondaryVideoPanel.addSecondaryVideoToList(filename, secondaryVideo);
        secondaryVideoPanel.setVideo(currentSecondaryVideo);
        CustomMenuItem menuItem = new CustomMenuItem(currentSecondaryVideo, secondaryVideoPanel, this);
        menuItem.setText(filename);
        jMenu3.add(menuItem);

    }

    private void saveToSystem(String output) {
        String filename = primaryVideoPanel.getFilename();
        filename = filename.substring(0, filename.indexOf("."));
        filename += ".meta";
        try {
            File file = new File(filename);
            BufferedWriter write;
            if (!file.exists()) {
                write = new BufferedWriter(new FileWriter(new File(filename)));
            } else {
                write = new BufferedWriter(new FileWriter(file, false));
            }
            write.write(output);
            write.close();

        } catch (IOException e) {
            System.err.println("Error saving file");
            e.printStackTrace();
        }
    }

    /**
     * just used for secondary view panel
     */
    public void resetScrollBar() {
        sVideoSlider.setValue(0);
        jTextField2.setText("0");
    }

    private byte[] getVideoFile(File file) {
        byte[] bytes = null;
        try {
            InputStream is = new FileInputStream(file);
            long len = file.length();
            try {
                bytes = new byte[(int) len];
                int offset = 0;
                int numRead = 0;
                while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                    offset += numRead;
                }

                is.close();
            } catch (OutOfMemoryError e) {
                if (currentSecondaryVideo > 0) {
                    //remove the first added video (assuming it is the "oldest" video and least likely to be needed
                    secondaryVideoPanel.removeOldestSecondaryVideo(jMenu3);
                    //secondaryVideoPanel.removeSecondaryVideo(currentSecondaryVideo,jMenu3);
                    currentSecondaryVideo--;
                    bytes = getVideoFile(file);
                } else {
                    System.err.println("Not enough java heap space to import video");
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bytes;
    }
}
